<template>
<div>
<!--  1.导航列表 使用面包屑 breadcrumb separator-class="el-icon-arrow-right"-->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{path: '/dashBook'}">首页</el-breadcrumb-item>
    <el-breadcrumb-item >学员信息管理父级菜单</el-breadcrumb-item>
    <el-breadcrumb-item >学员管理</el-breadcrumb-item>
  </el-breadcrumb>

  <!-- 2.el-卡片  el-card -->
  <el-card style="margin-top: 10px;">
  <!--  1.模糊查询区域  el-form 水平方向的表单-->
    <el-form :inline="true" :model="queryMap" label-width="100px;"
                                 size="small" style="margin: 12px 0;">
      <!--学员名称
      @keyup.enter.native="getStudentList"   按下回车键去查询学员列表数据
      clearable @clear="getStudentList" 清空输入框的值, 重新查询学员列表数据
      -->
      <el-form-item label="学员名称">
        <el-input type="text" v-model="queryMap.studentName" placeholder="请输入要查询的姓名"
        @keyup.enter.native="getStudentList" clearable @clear="getStudentList"></el-input>
      </el-form-item>
      <!--联系方式:电话号码-->
      <el-form-item label="联系方式">
        <el-input v-model="queryMap.studentPhone" placeholder="请输入要查询的电话号码"
        @keyup.enter.native="getStudentList" clearable @clear="getStudentList"></el-input>
      </el-form-item>
      <!--学员状态
      @visible-change="getStudentList"  下拉选中某一个值后,触发查询函数.
      -->
      <el-form-item label="学员状态">
        <el-select v-model="queryMap.studentStatus" clearable @clear="getStudentList"
                               placeholder="请选择要查询的状态" @visible-change="getStudentList">
          <el-option label="未报名" value="0"></el-option>
          <el-option label="在读" value="1"></el-option>
          <el-option label="退学" value="2"></el-option>
          <el-option label="休学" value="3"></el-option>
          <el-option label="开除" value="4"></el-option>
          <el-option label="自主就业" value="5"></el-option>
          <el-option label="已毕业" value="6"></el-option>
        </el-select>
      </el-form-item>
      <!--按钮区域-->
      <el-form-item>
        <el-button type="success" @click="getStudentList" icon="el-icon-search">查询</el-button>
        <el-button @click="resetForm" icon="el-icon-refresh"  type="info" plain>重置</el-button>
        <el-button type="primary" icon="el-icon-circle-plus-outline" @click="showStudentDialog">添加学员信息</el-button>
        <el-button type="info" icon="el-icon-download">导出</el-button>
      </el-form-item>
    </el-form>
  <!--    2.表格table区域-->
    <el-table :data="studentList" border stripe style="width: 100%;">
      <el-table-column label="学生编号" prop="studentId" width="90"></el-table-column>
      <el-table-column label="学生姓名" prop="studentName" width="80"></el-table-column>
      <el-table-column label="性别" prop="studentGender" width="60">
        <!-- 使用插槽[slot-scope="scope"]将性别转成中文显示-->
        <template slot-scope="scope">
          <span>{{scope.row.studentGender ==='0' ?"男":"女"}}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属班级" prop="className" width="100"></el-table-column>
      <el-table-column label="出生日期" prop="brithday" width="120"> </el-table-column>
      <el-table-column label="联系方式" prop="studentPhone" width="130"> </el-table-column>
      <el-table-column label="QQ号码" prop="qqAccount" width="110"> </el-table-column>
      <el-table-column label="联系地址" prop="studnetAddress" width="160"> </el-table-column>
      <el-table-column label="微信号" prop="wechatAaccout" width="100"> </el-table-column>
      <el-table-column label="邮箱" prop="email" width="120"></el-table-column>
      <el-table-column label="账号状态" prop="studentStatus">
        <template slot-scope="scope">
          <span>{{changeStatus(scope.row.studentStatus)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" >
        <template slot-scope="scope">
          <el-button size="small" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" icon="el-icon-delete"
                     @click="deleteStudenById(scope.row.studentId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  <!--  3.分页面组件
    background	是否为分页按钮添加背景色	boolean	—	false
    page-size	每页显示条目个数，支持 .sync 修饰符	number	—	10
    total	总条目数	number	—	—
    page-count	总页数，total 和 page-count 设置任意一个就可以达到显示页码的功能；如果要支持 page-sizes 的更改，则需要使用 total 属性	Number	—	—
    pager-count	页码按钮的数量，当总页数超过该值时会折叠	number	大于等于 5 且小于等于 21 的奇数	7
    current-page	当前页数，支持 .sync 修饰符	number	—	1
    layout	组件布局，子组件名用逗号分隔	String	sizes, prev, pager, next, jumper, ->, total, slot	'prev, pager, next, jumper, ->, total'
    page-sizes	每页显示个数选择器的选项设置	number[]	—	[10, 20, 30, 40, 50, 100]
  -->
    <el-pagination
    style="margin-top: 10px;"
    background
    @size-change="chanagePageSize"
    @current-change="changePageNum"
    :current-page="queryMap.pageNum"
    :page-size="queryMap.pageSize"
    :page-sizes="[5,10,20,30]"
    layout="total,sizes,prev,pager,next,jumper"
    :total="total"
    >
    </el-pagination>
  <!--  4.新增学员信息  -->
    <el-dialog :title="addOrUpdateStu" :visible.sync="addOrUpdateVisible" @close="cancelForm" width="60%">
      <span>
        <el-form :model="addForm" :label-position="labelPasition" :rules="addFormRlues" ref="addForm">
          <el-row>
            <el-col :span="11">
              <div class="grid-content bg-purple">
                <el-form-item label="学员姓名" prop="studentName">
                  <el-input type="text" v-model="addForm.studentName"
                            placeholder="请填写学员姓名" style="width: 400px"></el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="11">
              <div class="grid-content bg-purple-light">
                <el-form-item label="性别" prop="studentGender"> <!-- 学生性别:0男,1:女-->
                  <el-radio-group v-model="addForm.studentGender">
                    <el-radio label="0" :value="0">男</el-radio>
                    <el-radio label="1" :value="1">女</el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="11">
              <div class="grid-content bg-purple">
                <el-form-item label="联系电话" prop="studentPhone">
                  <el-input v-model="addForm.studentPhone"
                            placeholder="请输入电话号码"style="width: 400px"></el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="11">
              <div class="grid-content bg-purple">
                <el-form-item label="年龄">
                  <el-input v-model="addForm.studentAge"
                            placeholder="请输入年龄" style="width: 400px"></el-input>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <div class="grid-content bg-purple">
                <el-form-item label="QQ号码">
                  <el-input v-model="addForm.qqAccount"
                            placeholder="请输入QQ号码"style="width: 400px"></el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="11">
              <div class="grid-content bg-purple">
                <el-form-item label="微信号码">
                  <el-input v-model="addForm.wechatAaccout"
                            placeholder="请输入微信号码" style="width: 400px"></el-input>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <div class="grid-content bg-purple">
               <el-form-item label="身份证号码" prop="studentCard">
                 <el-input v-model="addForm.studentCard"
                           placeholder="请输入身份证号码" style="width: 380px;"></el-input>
               </el-form-item>
             </div>
            </el-col>
            <el-col :span="11">
              <div class="grid-content bg-purple">
               <el-form-item label="学员状态">
                 <el-select v-model="addForm.studentStatus" style="width: 400px;">
                   <el-option label="未报名" value="0"></el-option>
                   <el-option label="在读" value="1"></el-option>
                   <el-option label="退学" value="2"></el-option>
                   <el-option label="休学" value="3"></el-option>
                   <el-option label="开除" value="4"></el-option>
                   <el-option label="自主就业" value="5"></el-option>
                   <el-option label="已毕业" value="6"></el-option>
                 </el-select>
               </el-form-item>
             </div>
            </el-col>
          </el-row>

          <!--   第五行       -->
          <el-row>
            <el-col :span="11">
              <div class="grid-content bg-purple">
                <el-form-item label="出生日期">
                  <el-col :span="12">
                    <el-date-picker type="date" value-format="yyyy-MM-dd"
                    placeholder="请选择出生日期" v-model="addForm.brithday" style="width: 200px;"
                    ></el-date-picker>
                  </el-col>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="11">
              <div class="grid-content bg-purple">
                <el-form-item label="入学时间">
                  <el-col :span="12">
                    <el-date-picker type="date" value-format="yyyy-MM-dd"
                                    placeholder="请选择入学时间" v-model="addForm.enrolTime" style="width: 200px;"
                    ></el-date-picker>
                  </el-col>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
          <el-button round @click="cancelForm">取消</el-button>
          <el-button type="success"
                     @click="saveStudentInfo" round>保存</el-button>
      </span>
    </el-dialog>
  <!--  5.修改学员信息  -->
    <!--  6.删除学员信息  -->
    <!--  7.批量删除学员信息  -->
  <!-- 8,导出excel文件   -->
  </el-card>
</div>
</template>

<script>
export default {
  name: "StuManage",
  data(){
    //  声明一个常量, () =>{  箭头函数 它检验我们的手机号码,并且返回有值给checkPhone
    const checkPhone = (rule,value,callback) =>{

      // 正则表达式去校验我们手机号  11位
     const phoneRules = /^1[3456789]\d{9}$$/ ;
     // 判断是否为空
     if(!value){ // 输入框中没有填手机号码,那么就需要给以友情提示
       return callback(new Error("手机号码不能为空"))
     }
     // 判断手机号码是否为纯数字
     if(!Number.isInteger(+value)){
       return callback(new Error("请输入数字值的手机号码"))
     }else{
       //最后去判断符不符合手机号码以1开头,后面是3或者4或者5或者6或者7或者8或者9,并且后面跟9位自然数的规则
       if(!phoneRules.test(value)){
         return callback(new Error("您请输入手机号码格式不对"))
       }
       return callback(); // 校验通过直接返回
     }
    };
    const checkStudentCard = (rule,value,callback) =>{
      // 1.声明一个正则表达式的公式,改公式用于校验我们的身份证号码
      const cardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if(!value){
        return callback(new Error("身份证号码不能为空"))
      }
      if(cardReg.test(value)){
        return callback();
      }else{
        return callback(new Error("身份证号码格式不对,请重新输入!"))
      }
    }
    return {
      addFormRlues:{
        studentName: [
          {required: true, message: '请输入学员姓名', trigger: 'blur'},
          {min: 2, max: 10, message: '请输入长度为2-10个字符的名字', trigger: 'blur'}
        ],
        studentGender: [
          {required: true, message: '请选择性别', trigger: 'blur'}
        ],
        studentPhone: [
          { required: true, validator: checkPhone ,trigger: 'blur'}
        ],
        studentCard: [
          {
            required: true , validator: checkStudentCard, trigger: 'blur'
          }
        ]
      },
      addForm: {
        studentName: '',
        studentGender: '',
        studentPhone: '',
        studentAge: '',
        qqAccount: '',
        wechatAaccout: '',
        studentCard: '',
        studentStatus: '',
        brithday: '',
        enrolTime: '',
      },
      addOrUpdateStu: "新增学员信息",
      addOrUpdateVisible: false,  // 默认不弹框
      labelPasition: "right",
      total: 0,  // 总记录数
      studentList:[],
      queryMap: {
        pageNum: 1, // 当前页码,第几页
        pageSize: 5, // 每页显示5条数据
        studentName: '',
        studentPhone: '',
        studentStatus: ''
      }
    }
  },
  mounted() {
    // 当页面挂载扫浏览器进行渲染时,改函数被加载
    // 调用后台代码 获取学员集合数据
    this.getStudentList();
  },
  methods:{
    // 弹出编辑的对话框,
    /*
    * 然后去数据库查询该记录是否存在,存在显示在对话框里面,否则提示该记录不存在你
    */
    showEditDialog(student){
      // 1. 对话框的标题需要修改,
      this.addOrUpdateStu = '修改学员信息'
      // 2. 弹出对话框
      this.addOrUpdateVisible= true;
      // 3. 去数据库里面查询回显在对话框
      //this.addForm = student  // 直接将行记录传过赋值给form表单绑定的对象addForm   // 这种方式在企业开发不采用,这一种bug
      this.$http.get('student/edit/'+student.studentId).then(res =>{
        if(res.data.success){
          // 获取后台查询改学员信息的数据  赋值给addForm 对象
          this.addForm =res.data.data;
          //this.addForm.studentStatus = res.data.data.studentStatus + '' // 强制转换成String类型
          this.addForm.studentStatus = (res.data.data.studentStatus).toString(); // 调用toString方法转换成String类型
        }else{
          this.$message.error("该学员查无此数据",res.data.errorMsg)
          // 查不到学员信息,关闭对话框
          this.addOrUpdateVisible = false
          // 重新去查询列表数据
          this.getStudentList()
        }
      })
    },
    // 点击取消按钮
    cancelForm(){
      //清空表单校验信息
      this.$refs['addForm'].clearValidate();
      this.addForm = {}
      this.addOrUpdateVisible = false;
    },
    saveStudentInfo(){
     //点击保存去校验输入框或者下拉框,文本域等等是否输入了值
     this.$refs['addForm'].validate((valid) =>{
       if(valid){ // valid为true   条件成立:输入框或者下拉框,文本域输入满足条件的值
         // 新增 不需要传studentId
         if(!this.addForm.studentId){
            this.addStudent()
         }else{ //修改 需要传studentId
            this.updateStudent()
         }
       }else{
         this.$message.error("必填项不能为空,请重新输入!")
       }
     })

   },
    addStudent(){
      this.$http.post('student/add',this.addForm).then(res =>{
        if(!res.data.success){
          this.$message.error("保存学员信息失败",res.data.errorMsg)
        }
        this.addOrUpdateVisible = false
        this.getStudentList()
      })
    },
    updateStudent(){
      this.$http.put('student/update/'+this.addForm.studentId,this.addForm).then(res =>{
        if(res.data.success){ // 修改成功
          // 1.提示信息
          this.$notify({
            title: "操作成功",
            message: "学员信息已更新",
            type: "success"
          })
          // 2. 清空表单历史数据
          this.addForm = {}
          // 3. 修改完了,需要重新查询列表数据
          this.getStudentList()
        }else{ //  修改失败
          this.$notify({
            title: "操作失败",
            message: "学员信息修改失败" + res.data.errorMsg,
            type: "error"
          })
        }
        // 最后关闭 对话框
        this.addOrUpdateVisible = false
      })
    },
    // 点击添加按钮,弹出新增学员信息对话框
    showStudentDialog(){
      // 1.清除历史记录
      this.addForm = {}
      // 2.对话框弹出来
      this.addOrUpdateVisible = true
    },
    /*
    * 点击删除按钮,需要将数据库表:c_student对应的数据删除掉
    * 条件:根据学员的Id去删除
    * */
    async deleteStudenById(studentId){
      if(studentId){
        // 学生id 不为空的时候去操作删除
       const conf = await this.$confirm("您确定要删除此数据吗?",{
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: 'warning'
        }).catch(() =>{
          this.$message({
            type: "error",
            message: "已取消此操作"
          })
        })
        // 点击确定按钮 执行删除操作.
        if(conf === "confirm"){
         const {data : res} = await this.$http.delete('student/delete/'+studentId)
          console.log(res)
          if(res.success){
            this.$message.success("数据删除成功")
          }else{
            this.$message.error(res.data.errorMsg)
          }
        }
      }
    },
    /*
    * 点击重置,清空输入框和下拉框中的内容,说白了就是清空表单
    * */
    resetForm(){
      this.queryMap.studentName = ''
      this.queryMap.studentPhone = ''
      this.queryMap.studentStatus = ''
    },
    // 切换页码数
    changePageNum(newPageNum){
      // 改变 页码数,点击第一页,第二页...,重新赋值给查询对象queryMap里面的pageNum
      this.queryMap.pageNum = newPageNum
      //  最后在重新去查询一遍 学员表c_student
      this.getStudentList();
    },
    // 切换每页多少条的函数
    chanagePageSize(newSize){
      // 改变 每页显示多少条的数量,重新赋值给查询对象queryMap里面的pageSize
      this.queryMap.pageSize = newSize
      //  最后在重新去查询一遍 学员表c_student
      this.getStudentList();
    },
    //异步加载 学员集合数据
    async getStudentList(){
      const{data: res} = await this.$http.get('student/findList',{params:this.queryMap})
      console.log("获取学员集合数据",res)
      if(res.success){
        this.studentList = res.data.rows;
        this.total = res.data.total;
      }else{
        this.$message.error("查无此数据!")
      }
    },
    changeStatus(studentStatus){
      let statusInfo= "";
      if(studentStatus === 0){
        return statusInfo =  "未报名"
      }else if(studentStatus === 1){
        return statusInfo =  "在读"
      }else if(studentStatus === 2){
        return statusInfo =  "退学"
      }else if(studentStatus === 3){
        return statusInfo =  "休学"
      }else if(studentStatus === 4){
        return statusInfo =  "开除"
      }else if(studentStatus === 5){
        return statusInfo =  "自主就业"
      }else{
        return statusInfo =  "已毕业"
      }
    }

  }
}
</script>

<style scoped>

</style>
